package org.example.io.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.example.io.protocol.packet.LoginRequestPacket;
import org.example.io.protocol.packet.LoginResponsePacket;
import org.example.io.session.ServerSession;
import org.example.io.session.SessionUtil;
import org.example.io.util.LoginUtil;

import java.util.UUID;

/**
 * 登录处理器
 */
@Slf4j
public class LoginRequestPacketHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestPacket msg) throws Exception {
        if (valid(msg.getUserName(), msg.getPassword())) {
            LoginResponsePacket packet = new LoginResponsePacket();
            packet.setMessage("登录成功");
            packet.setSuccess(true);

            // 服务端和session双向绑定
            ServerSession serverSession = new ServerSession();
            serverSession.setSessionId(UUID.randomUUID().toString());
            serverSession.setUserName(msg.getUserName());
            LoginUtil.saveSession(serverSession, ctx.channel());
            ctx.channel().writeAndFlush(packet);
            SessionUtil.bindSession(serverSession, ctx.channel());
            log.info("【{}】登录成功", msg.getUserName());
        } else {
            // 如果登录失败，提示未登录，并且连接关闭
            LoginResponsePacket packet = new LoginResponsePacket();
            packet.setMessage("登录失败，请确认用户名和密码是否正确");
            packet.setSuccess(false);
            ctx.channel().writeAndFlush(packet);
        }
    }

    public boolean valid(String username, String password) {
        return true;
    }
}
